<template>
  <div class="profile-page">
    <h2 class="page-title">个人资料</h2>
    <el-form :model="form" label-width="100px" class="profile-form">
      <el-form-item label="头像">
        <el-upload class="avatar-uploader" action="#" :show-file-list="false" :auto-upload="false"
          :on-change="handleAvatarChange">
          <el-avatar :size="100" :src="form.avatar">
            <el-icon :size="40">
              <User />
            </el-icon>
          </el-avatar>
          <div class="upload-tip">点击更换头像</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="form.nickname" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="form.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="个人简介">
        <el-input v-model="form.bio" type="textarea" :rows="4" placeholder="介绍一下自己吧" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSave">保存修改</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user/index.js'

const userStore = useUserStore()

const form = reactive({
  avatar: '',
  username: '',
  nickname: '',
  email: '',
  phone: '',
  bio: ''
})

const loadUserInfo = () => {
  Object.assign(form, {
    avatar: userStore.userInfo?.avatar || '',
    username: userStore.userInfo?.username || '',
    nickname: userStore.userInfo?.nickname || '',
    email: userStore.userInfo?.email || '',
    phone: userStore.userInfo?.phone || '',
    bio: userStore.userInfo?.bio || ''
  })
}

const handleAvatarChange = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    form.avatar = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

const handleSave = () => {
  console.log('保存个人资料:', form)
  ElMessage.success('个人资料保存成功')
  // 调用 API 保存
}

const handleReset = () => {
  loadUserInfo()
  ElMessage.info('已重置')
}

onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped lang="less">
.profile-page {
  .page-title {
    font-size: 24px;
    font-weight: 700;
    color: #1a1a1a;
    margin: 0 0 32px 0;
  }

  .profile-form {
    max-width: 600px;
  }

  .avatar-uploader {
    text-align: center;

    .upload-tip {
      margin-left: 20px;
      margin-top: 12px;
      font-size: 13px;
      color: #999;
    }

    :deep(.el-upload) {
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        opacity: 0.8;
      }
    }
  }
}
</style>
